import * as express from "express";

import {User} from "../models/User";
import {TokensService} from '../services/TokensService';
export class BaseController
{
  app:express.Application;
  tokensService:TokensService;
  domain:string="/kapi";
  constructor(app:express.Application)
  {
    this.app = app;
    this.tokensService = new TokensService();
  }

  initResponse(res: express.Response)
  {
    res.header("Content-Type","application/json");
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type,Content-Length, Accept,Referer,Accept-Language,User-Agent,x-token,x-username,x-password');
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  }

  validateUser(req: express.Request,res: express.Response,success:Function,fail?:Function)
  {
    var tokenStr:string = req.header("x-token");
    this.tokensService.get(tokenStr,(err,user:User)=>{
      if(user!==undefined)
      {
        success(user);
      }else
      {
        fail && fail();
        if(!fail)
        {
          res.send({msg:"auth is error!"});
        }
      }
    })
  }

  handerErr(req:express.Request,res:express.Response,handler:Function,checkToken?:Boolean)
  {
    try{
      this.initResponse(res);
      var contenttype = req.header("Content-Type") || "";
      contenttype = contenttype.toLowerCase();
      if(contenttype.indexOf("application/json")<0 && req.method.toLowerCase() != "get" && req.method.toLowerCase() != "delete"&& req.method.toLowerCase() != "options")
      {
        res.statusCode = 400;
        res.send({msg:"Please set Request Content-Type is application/json."})
        return;
      }
      if(checkToken)
      {
        this.validateUser(req,res,(user:User)=>{
          handler && handler(user)
        })
      }else{
        handler && handler()
      }
    }catch(ex)
    {
      //打印出错误
      console.log(ex);
      //打印出错误的调用栈方便调试
      console.log(ex.stack);

      res.statusCode = 500;
      res.send({msg:"server have a error!"})
    }
  }

}
